{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Google AlloyDB for PostgreSQL\n",
    "\n",
    "> [AlloyDB](https://cloud.google.com/alloydb) is a fully managed relational database service that offers high performance, seamless integration, and impressive scalability. AlloyDB is 100% compatible with PostgreSQL. Extend your database application to build AI-powered experiences leveraging AlloyDB's Langchain integrations.\n",
    "\n",
    "This notebook goes over how to use `AlloyDB for PostgreSQL` to store vector embeddings with the `AlloyDBVectorStore` class.\n",
    "\n",
    "Learn more about the package on [GitHub](https://github.com/googleapis/langchain-google-alloydb-pg-python/).\n",
    "\n",
    "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/googleapis/langchain-google-alloydb-pg-python/blob/main/docs/vector_store.ipynb)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Before you begin\n",
    "\n",
    "To run this notebook, you will need to do the following:\n",
    "\n",
    " * [Create a Google Cloud Project](https://developers.google.com/workspace/guides/create-project)\n",
    " * [Enable the AlloyDB API](https://console.cloud.google.com/flows/enableapi?apiid=alloydb.googleapis.com)\n",
    " * [Create a AlloyDB cluster and instance.](https://cloud.google.com/alloydb/docs/cluster-create)\n",
    " * [Create a AlloyDB database.](https://cloud.google.com/alloydb/docs/quickstart/create-and-connect)\n",
    " * [Add a User to the database.](https://cloud.google.com/alloydb/docs/database-users/about)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "IR54BmgvdHT_"
   },
   "source": [
    "### 🦜🔗 Library Installation\n",
    "Install the integration library, `langchain-google-alloydb-pg`, and the library for the embedding service, `langchain-google-vertexai`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 1000
    },
    "id": "0ZITIDE160OD",
    "outputId": "e184bc0d-6541-4e0a-82d2-1e216db00a2d"
   },
   "outputs": [],
   "source": [
    "%pip install --upgrade --quiet  langchain-google-alloydb-pg langchain-google-vertexai"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "v40bB_GMcr9f"
   },
   "source": [
    "**Colab only:** Uncomment the following cell to restart the kernel or use the button to restart the kernel. For Vertex AI Workbench you can restart the terminal using the button on top."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "v6jBDnYnNM08",
   "metadata": {
    "id": "v6jBDnYnNM08"
   },
   "outputs": [],
   "source": [
    "# # Automatically restart kernel after installs so that your environment can access the new packages\n",
    "# import IPython\n",
    "\n",
    "# app = IPython.Application.instance()\n",
    "# app.kernel.do_shutdown(True)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "yygMe6rPWxHS",
   "metadata": {
    "id": "yygMe6rPWxHS"
   },
   "source": [
    "### 🔐 Authentication\n",
    "Authenticate to Google Cloud as the IAM user logged into this notebook in order to access your Google Cloud Project.\n",
    "\n",
    "* If you are using Colab to run this notebook, use the cell below and continue.\n",
    "* If you are using Vertex AI Workbench, check out the setup instructions [here](https://github.com/GoogleCloudPlatform/generative-ai/tree/main/setup-env)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "PTXN1_DSXj2b",
   "metadata": {
    "id": "PTXN1_DSXj2b"
   },
   "outputs": [],
   "source": [
    "from google.colab import auth\n",
    "\n",
    "auth.authenticate_user()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "NEvB9BoLEulY",
   "metadata": {
    "id": "NEvB9BoLEulY"
   },
   "source": [
    "### ☁ Set Your Google Cloud Project\n",
    "Set your Google Cloud project so that you can leverage Google Cloud resources within this notebook.\n",
    "\n",
    "If you don't know your project ID, try the following:\n",
    "\n",
    "* Run `gcloud config list`.\n",
    "* Run `gcloud projects list`.\n",
    "* See the support page: [Locate the project ID](https://support.google.com/googleapi/answer/7014113)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "gfkS3yVRE4_W",
   "metadata": {
    "cellView": "form",
    "id": "gfkS3yVRE4_W"
   },
   "outputs": [],
   "source": [
    "# @markdown Please fill in the value below with your Google Cloud project ID and then run the cell.\n",
    "\n",
    "PROJECT_ID = \"my-project-id\"  # @param {type:\"string\"}\n",
    "\n",
    "# Set the project id\n",
    "!gcloud config set project {PROJECT_ID}"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f8f2830ee9ca1e01",
   "metadata": {
    "id": "f8f2830ee9ca1e01"
   },
   "source": [
    "## Basic Usage"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "OMvzMWRrR6n7",
   "metadata": {
    "id": "OMvzMWRrR6n7"
   },
   "source": [
    "### Set AlloyDB database values\n",
    "Find your database values, in the [AlloyDB Instances page](https://console.cloud.google.com/alloydb/clusters)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "irl7eMFnSPZr",
   "metadata": {
    "id": "irl7eMFnSPZr"
   },
   "outputs": [],
   "source": [
    "# @title Set Your Values Here { display-mode: \"form\" }\n",
    "REGION = \"us-central1\"  # @param {type: \"string\"}\n",
    "CLUSTER = \"my-cluster\"  # @param {type: \"string\"}\n",
    "INSTANCE = \"my-primary\"  # @param {type: \"string\"}\n",
    "DATABASE = \"my-database\"  # @param {type: \"string\"}\n",
    "TABLE_NAME = \"vector_store\"  # @param {type: \"string\"}"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "QuQigs4UoFQ2",
   "metadata": {
    "id": "QuQigs4UoFQ2"
   },
   "source": [
    "### AlloyDBEngine Connection Pool\n",
    "\n",
    "One of the requirements and arguments to establish AlloyDB as a vector store is a `AlloyDBEngine` object. The `AlloyDBEngine`  configures a connection pool to your AlloyDB database, enabling successful connections from your application and following industry best practices.\n",
    "\n",
    "To create a `AlloyDBEngine` using `AlloyDBEngine.from_instance()` you need to provide only 5 things:\n",
    "\n",
    "1. `project_id` : Project ID of the Google Cloud Project where the AlloyDB instance is located.\n",
    "1. `region` : Region where the AlloyDB instance is located.\n",
    "1. `cluster`: The name of the AlloyDB cluster.\n",
    "1. `instance` : The name of the AlloyDB instance.\n",
    "1. `database` : The name of the database to connect to on the AlloyDB instance.\n",
    "\n",
    "By default, [IAM database authentication](https://cloud.google.com/alloydb/docs/connect-iam) will be used as the method of database authentication. This library uses the IAM principal belonging to the [Application Default Credentials (ADC)](https://cloud.google.com/docs/authentication/application-default-credentials) sourced from the environment.\n",
    "\n",
    "Optionally, [built-in database authentication](https://cloud.google.com/alloydb/docs/database-users/about) using a username and password to access the AlloyDB database can also be used. Just provide the optional `user` and `password` arguments to `AlloyDBEngine.from_instance()`:\n",
    "\n",
    "* `user` : Database user to use for built-in database authentication and login\n",
    "* `password` : Database password to use for built-in database authentication and login.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Note:** This tutorial demonstrates the async interface. All async methods have corresponding sync methods."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain_google_alloydb_pg import AlloyDBEngine\n",
    "\n",
    "engine = await AlloyDBEngine.afrom_instance(\n",
    "    project_id=PROJECT_ID,\n",
    "    region=REGION,\n",
    "    cluster=CLUSTER,\n",
    "    instance=INSTANCE,\n",
    "    database=DATABASE,\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "D9Xs2qhm6X56"
   },
   "source": [
    "### Initialize a table\n",
    "The `AlloyDBVectorStore` class requires a database table. The `AlloyDBEngine` engine has a helper method `init_vectorstore_table()` that can be used to create a table with the proper schema for you."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "metadata": {
    "id": "avlyHEMn6gzU"
   },
   "outputs": [],
   "source": [
    "await engine.ainit_vectorstore_table(\n",
    "    table_name=TABLE_NAME,\n",
    "    vector_size=768,  # Vector size for VertexAI model(textembedding-gecko@latest)\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Create an embedding class instance\n",
    "\n",
    "You can use any [LangChain embeddings model](/docs/integrations/text_embedding/).\n",
    "You may need to enable Vertex AI API to use `VertexAIEmbeddings`. We recommend setting the embedding model's version for production, learn more about the [Text embeddings models](https://cloud.google.com/vertex-ai/docs/generative-ai/model-reference/text-embeddings)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "5utKIdq7KYi5",
   "metadata": {
    "id": "5utKIdq7KYi5"
   },
   "outputs": [],
   "source": [
    "# enable Vertex AI API\n",
    "!gcloud services enable aiplatform.googleapis.com"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "Vb2RJocV9_LQ",
    "outputId": "37f5dc74-2512-47b2-c135-f34c10afdcf4"
   },
   "outputs": [],
   "source": [
    "from langchain_google_vertexai import VertexAIEmbeddings\n",
    "\n",
    "embedding = VertexAIEmbeddings(\n",
    "    model_name=\"textembedding-gecko@latest\", project=PROJECT_ID\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "e1tl0aNx7SWy"
   },
   "source": [
    "### Initialize a default AlloyDBVectorStore"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "z-AZyzAQ7bsf"
   },
   "outputs": [],
   "source": [
    "from langchain_google_alloydb_pg import AlloyDBVectorStore\n",
    "\n",
    "store = await AlloyDBVectorStore.create(\n",
    "    engine=engine,\n",
    "    table_name=TABLE_NAME,\n",
    "    embedding_service=embedding,\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Add texts"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import uuid\n",
    "\n",
    "all_texts = [\"Apples and oranges\", \"Cars and airplanes\", \"Pineapple\", \"Train\", \"Banana\"]\n",
    "metadatas = [{\"len\": len(t)} for t in all_texts]\n",
    "ids = [str(uuid.uuid4()) for _ in all_texts]\n",
    "\n",
    "await store.aadd_texts(all_texts, metadatas=metadatas, ids=ids)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Delete texts"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "await store.adelete([ids[1]])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Search for documents"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "query = \"I'd like a fruit.\"\n",
    "docs = await store.asimilarity_search(query)\n",
    "print(docs)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Search for documents by vector"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "query_vector = embedding.embed_query(query)\n",
    "docs = await store.asimilarity_search_by_vector(query_vector, k=2)\n",
    "print(docs)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Add a Index\n",
    "Speed up vector search queries by applying a vector index. Learn more about [vector indexes](https://cloud.google.com/blog/products/databases/faster-similarity-search-performance-with-pgvector-indexes)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain_google_alloydb_pg.indexes import IVFFlatIndex\n",
    "\n",
    "index = IVFFlatIndex()\n",
    "await store.aapply_vector_index(index)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Re-index"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "await store.areindex()  # Re-index using default index name"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Remove an index"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "await store.adrop_vector_index()  # Delete index using default name"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Create a custom Vector Store\n",
    "A Vector Store can take advantage of relational data to filter similarity searches.\n",
    "\n",
    "Create a table with custom metadata columns."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain_google_alloydb_pg import Column\n",
    "\n",
    "# Set table name\n",
    "TABLE_NAME = \"vectorstore_custom\"\n",
    "\n",
    "await engine.ainit_vectorstore_table(\n",
    "    table_name=TABLE_NAME,\n",
    "    vector_size=768,  # VertexAI model: textembedding-gecko@latest\n",
    "    metadata_columns=[Column(\"len\", \"INTEGER\")],\n",
    ")\n",
    "\n",
    "\n",
    "# Initialize AlloyDBVectorStore\n",
    "custom_store = await AlloyDBVectorStore.create(\n",
    "    engine=engine,\n",
    "    table_name=TABLE_NAME,\n",
    "    embedding_service=embedding,\n",
    "    metadata_columns=[\"len\"],\n",
    "    # Connect to a existing VectorStore by customizing the table schema:\n",
    "    # id_column=\"uuid\",\n",
    "    # content_column=\"documents\",\n",
    "    # embedding_column=\"vectors\",\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Search for documents with metadata filter"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import uuid\n",
    "\n",
    "# Add texts to the Vector Store\n",
    "all_texts = [\"Apples and oranges\", \"Cars and airplanes\", \"Pineapple\", \"Train\", \"Banana\"]\n",
    "metadatas = [{\"len\": len(t)} for t in all_texts]\n",
    "ids = [str(uuid.uuid4()) for _ in all_texts]\n",
    "await store.aadd_texts(all_texts, metadatas=metadatas, ids=ids)\n",
    "\n",
    "# Use filter on search\n",
    "docs = await custom_store.asimilarity_search_by_vector(query_vector, filter=\"len >= 6\")\n",
    "\n",
    "print(docs)"
   ]
  }
 ],
 "metadata": {
  "colab": {
   "provenance": [],
   "toc_visible": true
  },
  "kernelspec": {
   "display_name": "Python 3",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
